package com.mowanka.mokeng.ui.adapter

import android.os.CountDownTimer
import android.os.Handler
import android.text.Html
import android.util.TypedValue
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.TimeUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.mowanka.mokeng.R
import com.mowanka.mokeng.app.ext.pt2px
import com.mowanka.mokeng.app.ext.removeZero
import com.mowanka.mokeng.app.ext.timeFormat
import com.mowanka.mokeng.app.weight.imageview.RoundCorner
import com.mowanka.mokeng.app.weight.recyclerview.decoration.FlowSpacingItemDecoration
import com.mowanka.mokeng.app.weight.recyclerview.layoutmanager.FlowLayoutManager
import com.mowanka.mokeng.data.model.bean.CommentProduct
import java.util.*
import kotlin.math.floor
import kotlin.math.min

class CommentProductAdapter(data: MutableList<CommentProduct>, private var systemDate: Date? = null) :
    BaseQuickAdapter<CommentProduct, BaseViewHolder>(R.layout.comment_product_item, data) {
    //用于倒计时
    private val timeMap by lazy { mutableMapOf<TextView, MyCountDownTimer>() }
    private val handler by lazy { Handler() }
    private val runnable by lazy {
        object : Runnable {
            override fun run() {
                systemDate?.let {
                    it.time = it.time + 1000
                    handler.postDelayed(this, 1000)
                }
            }
        }
    }

    private val mPhotoWidth : Int by lazy { context.pt2px(176) }

    override fun convert(helper: BaseViewHolder, item: CommentProduct) {
        with(helper) {
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,16f, context.resources.displayMetrics)

            //图片
            getView<ImageView>(R.id.comment_product_item_pic).apply {
                if (item.coverHeight > 0 && item.coverWidth > 0) {
                    layoutParams.width = mPhotoWidth
                    layoutParams.height = min(mPhotoWidth * item.coverHeight / item.coverWidth, context.pt2px(220))
                } else {
                    layoutParams.width = mPhotoWidth
                    layoutParams.height = mPhotoWidth
                }
            }
            Glide.with(context)
                .load(item.coverPic)
                .thumbnail(0.1f)
                .placeholder(R.drawable.shape_c_eeeeee_8)
                .apply(
                    RequestOptions().transform(
                        RoundCorner(
                            context,
                            leftTop = 8,
                            rightTop = 8
                        )
                    )
                )
                .into(getView(R.id.comment_product_item_pic))
            setGone(R.id.comment_product_item_state_image, item.sellout)
            setGone(R.id.comment_product_item_new, item.isNew)
            setGone(R.id.comment_product_item_shang, item.isDsl)
            if (item.stateStr.isNullOrEmpty() && item.endTime.isNullOrEmpty()) {
                setGone(R.id.comment_product_item_state_text, false)
            } else if (!item.stateStr.isNullOrEmpty()) {
                setGone(R.id.comment_product_item_state_text, true)
                setText(R.id.comment_product_item_state_text, item.stateStr)
            } else {
                setGone(R.id.comment_product_item_state_text, true)
                startTimer(getView(R.id.comment_product_item_state_text), item.endTime)
            }
            //名称
            setText(R.id.comment_product_item_content, Html.fromHtml(item.content))
            //价格行
            setGone(R.id.comment_product_item_price_pre, !item.pricePre.isNullOrEmpty())
            setText(R.id.comment_product_item_price_pre, item.pricePre)
            setText(R.id.comment_product_item_price, item.price.removeZero())
            setGone(R.id.comment_product_item_price_post, !item.pricePost.isNullOrEmpty())
            setText(R.id.comment_product_item_price_post, item.pricePost)
            setGone(R.id.comment_product_item_extra, !item.extra.isNullOrEmpty())
            setText(R.id.comment_product_item_extra, item.extra)

            //标签
            if (item.labelList.isNullOrEmpty()) {
                setGone(R.id.product_recommend_item_label, false)
            } else {
                setGone(R.id.product_recommend_item_label, true)
                val labelRecycler = getView<RecyclerView>(R.id.product_recommend_item_label)
                labelRecycler.layoutManager = FlowLayoutManager()
                if (labelRecycler.itemDecorationCount == 0) labelRecycler.addItemDecoration(FlowSpacingItemDecoration(context.pt2px(4)))
                labelRecycler.adapter = LabelAdapter(item.labelList)
            }
            //选中
            setGone(R.id.product_recommend_item_selected, item.isSelect)
        }
    }

    init {
        systemDate?.let {
            handler.postDelayed(runnable, 1000)
        }
    }

    private fun startTimer(tvTime: TextView, endTime: String?) {
        systemDate?.let {
            if (endTime.isNullOrEmpty()) return
            stopTimer(tvTime)
            //创建倒计时，与控件绑定
            val time = getDistanceTimeLong(it, TimeUtils.string2Date(endTime, "yyyy-MM-dd HH:mm:ss"))
            if (time > 0) {
                val cdu = MyCountDownTimer(time, 1000, tvTime)
                cdu.start()
                timeMap[tvTime] = cdu
            }
        }
    }

    private fun stopTimer(tvTime: TextView) {
        var tc: MyCountDownTimer? = timeMap[tvTime]
        if (tc != null) {
            tc.cancel()
            tc = null
        }
    }

    /**
     * 时间工具，返回间隔时间长
     */
    private fun getDistanceTimeLong(one: Date, two: Date): Long {
        var diff = 0L
        try {
            diff = two.time - one.time
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return diff
    }

    /**
     * 退出时清空所有item的计时器
     */
    fun cancelAllTimers() {
        var s: Set<MutableMap.MutableEntry<TextView, MyCountDownTimer>>? = timeMap.entries
        var it: Iterator<*>? = s!!.iterator()
        while (it!!.hasNext()) {
            try {
                val pairs = it.next() as MutableMap.MutableEntry<*, *>
                var cdt: MyCountDownTimer? = pairs.value as MyCountDownTimer
                cdt!!.cancel()
                cdt = null
            } catch (e: Exception) {
            }

        }
        it = null
        s = null
        timeMap.clear()
    }

    fun removeTimer() {
        handler.removeCallbacks(runnable)
    }

    fun reSetTimer(date: Date) {
        cancelAllTimers()
        removeTimer()
        systemDate = date
        handler.postDelayed(runnable, 1000)
    }

    /**
     * 倒计时类，每间隔countDownInterval时间调用一次onTick()
     */
    private inner class MyCountDownTimer(
        millisInFuture: Long,
        var countDownInterval: Long,
        var tv: TextView
    ) : CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            //设置时间格式
            val m = floor(millisUntilFinished / countDownInterval.toDouble()).toLong()
            val day = m / (60 * 60 * 24)
            val hour = m / (60 * 60) % 24
            val minute = (m / 60) % 60
            tv.text = context.getString(R.string.auction_left_time, day.toString(), hour.timeFormat(), minute.timeFormat())
        }

        override fun onFinish() {
            
        }
    }
}